<template>
  <div class="app-container">
    <div class="page-card">
      <div class="page-form">
        <el-select
          placeholder="学校"
          v-model="queryParams.deptId"
          filterable
          @change="
            queryParams.classId = '';
            handleSearch();
          "
          clearable
          v-hasRole="['admin']"
        >
          <el-option
            v-for="dict in deptList"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId.toString()"
          />
        </el-select>
        <el-select
          v-model="queryParams.gradeId"
          placeholder="年级"
          clearable
          @change="
            queryParams.classId = '';
            handleSearch();
          "
        >
          <el-option
            v-for="dict in dict.type.grade"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-select
          v-model="queryParams.classId"
          placeholder="班级"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in queryParamsBjlb"
            :key="dict.id"
            :label="dict.className"
            :value="dict.id.toString()"
          />
        </el-select>
        <el-select
          v-model="queryParams.selectSubject"
          placeholder="选科"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="dict in xklb"
            :key="dict.subjectId"
            :label="dict.subjectName"
            :value="dict.subjectName"
          />
        </el-select>
        <el-input
          v-model="queryParams.examNo"
          placeholder="准考证号"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.studentName"
          placeholder="学生姓名"
          clearable
          @input="handleSearch"
        />
      </div>
      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          label="ID"
          align="center"
          prop="id"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column
          label="所属学校"
          align="center"
          prop="schoolName"
          :show-overflow-tooltip="true"
          width="140"
        />
        <el-table-column
          label="姓名"
          align="center"
          prop="studentName"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="学号"
          align="center"
          prop="studentNo"
          :show-overflow-tooltip="true"
          width="140"
        />
        <el-table-column
          label="准考证号"
          align="center"
          prop="examNo"
          :show-overflow-tooltip="true"
          width="140"
        />
        <el-table-column
          label="学段"
          align="center"
          prop="stage"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column
          label="年级"
          align="center"
          prop="grade"
          :show-overflow-tooltip="true"
          width="100"
        />

        <el-table-column
          label="班级"
          align="center"
          prop="className"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column
          label="选科"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <km-tag
              v-for="v in scope.row.selectSubjectList"
              :key="v.subjectId"
              :option="v.subjectName"
            ></km-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="小语种"
          align="center"
          prop="minorLanguage"
          :show-overflow-tooltip="true"
          width="100"
        >
          <template slot-scope="scope">
            <km-tag
              v-if="scope.row.minorLanguage"
              :option="scope.row.minorLanguage"
            ></km-tag>
          </template>
        </el-table-column> -->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="140"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
            <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-bottom">
      <div class="sel-box">
        <p>共 {{ total }} 项</p>
        <el-button type="primary" @click="edit(false)">新增学生</el-button>
        <el-button type="primary" @click="upload.open = true"
          >批量导入</el-button
        >
        <el-button type="danger" :disabled="multiple" @click="del(false)"
          >批量删除</el-button
        >
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑学生"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="editForm.studentName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="editForm.studentNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="准考证号" prop="examNo">
          <el-input v-model="editForm.examNo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="所属学校"
          prop="deptId"
          @change="editForm.classId = ''"
          v-hasRole="['admin']"
        >
          <el-select v-model="editForm.deptId" filterable>
            <el-option
              v-for="dict in deptList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学段" prop="stageId">
          <el-select v-model="editForm.stageId" @change="editForm.gradeId = ''">
            <el-option
              v-for="dict in dict.type.school_segment_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="gradeId">
          <el-select v-model="editForm.gradeId" @change="editForm.classId = ''">
            <el-option
              v-for="dict in dict.type['grade' + editForm.stageId]"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="editForm.classId">
            <el-option
              v-for="dict in bjlb"
              :key="dict.id"
              :label="dict.className"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选科" prop="subject">
          <el-select v-model="editForm.subject" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.subjectId"
              :label="dict.subjectName"
              :value="dict.subjectId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="小语种" prop="minorLanguage">
          <el-select v-model="editForm.minorLanguage">
            <el-option
              v-for="dict in xklb"
              :key="dict.subjectId"
              :label="dict.subjectName"
              :value="dict.subjectName"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="导入"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  studentlist,
  studentAdd,
  studentEdit,
  studentDel,
} from "@/api/jcgl/xsgl";
import { classlist } from "@/api/jcgl/bjgl";
import { listDept } from "@/api/system/dept";
import { subjectlistselect } from "@/api/common";
import { debounce } from "lodash";
export default {
  name: "Basic_xsgl",
  dicts: ["school_segment_type", "grade", "grade1", "grade2", "grade3"],
  data() {
    return {
      firstLoad: true,
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
        deptId:
          this.$route.query.deptId ||
          (this.$auth.hasRole("admin") ? "" : this.$store.state.user.deptId),
        gradeId: this.$route.query.gradeId,
        classId: this.$route.query.classId,
        examNo: "",
        studentName: "",
        selectSubject: "",
      },

      editKmVisible: false,
      editForm: {
        studentName: "",
        studentNo: "",
        examNo: "",
        stageId: "",
        gradeId: "",
        classId: "",
        subject: [],
        // minorLanguage: "",
        deptId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
      },
      rules: {
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "blur" },
        ],
        examNo: [
          { required: true, message: "准考证号不能为空", trigger: "blur" },
        ],
        stageId: [
          { required: true, message: "学段不能为空", trigger: "change" },
        ],
        gradeId: [
          { required: true, message: "年级不能为空", trigger: "change" },
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "change" },
        ],
        subject: [
          { required: true, message: "选科不能为空", trigger: "change" },
        ],
        // minorLanguage: [
        //   { required: true, message: "小语种不能为空", trigger: "change" },
        // ],
        deptId: [
          { required: true, message: "学校不能为空", trigger: "change" },
        ],
      },

      allbjlb: [],
      xklb: [],
      deptList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/student/import",
      },
    };
  },
  computed: {
    bjlb: function () {
      return this.allbjlb.filter((item) => {
        return (
          this.editForm.gradeId.indexOf(item.gradeId.toString()) != -1 &&
          item.schoolId == this.editForm.deptId
        );
      });
    },
    queryParamsBjlb: function () {
      return this.allbjlb.filter((item) => {
        return (
          this.queryParams.gradeId == item.gradeId &&
          item.schoolId == this.queryParams.deptId
        );
      });
    },
  },
  created() {
    this.getList();

    classlist({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.allbjlb = res.rows;
    });
    subjectlistselect("-1").then((res) => {
      this.xklb = res.data;
    });
    if (this.$auth.hasRole("admin")) {
      listDept().then((res) => {
        this.deptList = res.data.filter((item) => {
          return item.type == 1;
        });
      });
    }
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  methods: {
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    getList() {
      this.loading = true;
      this.tableData = [];
      studentlist(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    edit(row) {
      if (row) {
        this.editForm.id = row.id;
        this.editForm.studentName = row.studentName;
        this.editForm.studentNo = row.studentNo;
        this.editForm.examNo = row.examNo;
        this.editForm.stageId = row.stageId.toString();
        this.editForm.gradeId = row.gradeId.toString();
        this.editForm.classId = row.classId;
        // this.editForm.minorLanguage = row.minorLanguage;
        this.editForm.deptId = row.deptId;

        if (row.selectSubjectList) {
          this.editForm.subject = row.selectSubjectList.map((item) => {
            return item.subjectId;
          });
        }
      }

      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        studentName: "",
        studentNo: "",
        examNo: "",
        stageId: "",
        gradeId: "",
        classId: "",
        subject: [],
        // minorLanguage: "",
        deptId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = studentEdit;
          } else {
            req = studentAdd;
          }
          let data = {
            ...this.editForm,
          };

          data.stage = this.selectDictLabel(
            this.dict.type.school_segment_type,
            data.stageId
          );
          data.grade = this.selectDictLabel(this.dict.type.grade, data.gradeId);
          let classData = this.bjlb.filter((item) => {
            return item.id == data.classId;
          })[0];
          data.class = classData.className;
          let selectSubject = [];
          this.xklb.map((item) => {
            if (data.subject.indexOf(item.subjectId) != -1) {
              selectSubject.push({
                subjectId: item.subjectId,
                subjectName: item.subjectName,
              });
            }
          });
          data.selectSubject = selectSubject;

          data.schoolId = data.deptId;

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    del(id) {
      this.$modal.confirm("请确认进行删除操作").then(() => {
        studentDel({ ids: id ? [id] : this.ids }).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },

    handleSearch() {
      this.debouncedSearch();
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://bs-exam-bucket.oss-cn-beijing.aliyuncs.com/dev/bsta/exam/uploadPath/upload/template/student_template.xlsx"
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 240px;
  }
}
</style>